import axios from 'axios'
import { Message, MessageBox } from 'element-ui'
import router from '../router'
import settings from '../settings'

axios.defaults.withCredentials = false

// create an axios instance
const service = axios.create({
  baseURL: '', // api的base_url
  timeout: 30000 // 请求超时时间
})

// request拦截器
service.interceptors.request.use(config => {
  if (settings.sso) {
    const authorizationToken = localStorage.getItem('access_token')
    const systemId = window.systemId
    config.headers = {
      'Content-Type': 'application/json',
      Authorization: authorizationToken,
      SystemID: systemId
    }
  }
  return config
}, error => {
  // Do something with request error
  console.log(error) // for debug
  return Promise.reject(error)
})

// response interceptor
service.interceptors.response.use(
  response => {
    /**
     * code为非200抛错 可结合自己业务进行修改
     */
    const data = response.data
    if (data.code === 500) {
      Message({
        message: data.msg,
        type: 'error',
        duration: 5 * 1000
      })
      // eslint-disable-next-line prefer-promise-reject-errors
      return Promise.reject(data.msg)
    } else if (data.code === 401) {
      // 清除前台token信息
      window.localStorage.clear()
      // eslint-disable-next-line prefer-promise-reject-errors
      return Promise.reject(data.msg)
    } else {
      return response.data
    }
  },
  error => {
    if (settings.sso) {
      // Http错误处理
      const status = error.response.status
	  const message = error.response.data && error.response.data.message ? error.response.data.message : '用户认证失败，请重新登录账户'
      if (status === 401) {
        // 清除前台token信息
        window.localStorage.clear()
        // oauth2权限认证失败
        // 需要跳转登录页
        var returnUrl = "";
        if(this.$route.query.returnUrl){
          returnUrl = decodeURIComponent(this.$route.fullPath).split("returnUrl=")[1]
        }else{
          returnUrl = window.location.href
        }
        // 检查是否正在显示提示框
        if (document.getElementsByClassName('authority-error-box').length < 1) {
          MessageBox.alert(message, '', {
            type: 'error',
            customClass: 'authority-error-box',
            confirmButtonText: '确定',
            callback: action => {
              router.push({ path: '/login?returnUrl=' + returnUrl })
            }
          })
        } else {
          const alertParent = document.getElementsByClassName('authority-error-box')[0].parentElement
          const isHidden = alertParent.style.display === 'none'
          if (isHidden) {
            MessageBox.alert(message, '', {
              type: 'error',
              customClass: 'authority-error-box',
              confirmButtonText: '确定',
              callback: action => {
                router.push({ path: '/login?returnUrl=' + returnUrl })
              }
            })
          }
        }
        return Promise.reject(error)
      } else {
        if (error.response.data.msg !== undefined) {
          Message({
            message: error.response.data.msg,
            type: 'error',
            duration: 5 * 1000
          })
        } else {
          Message({
            message: '后台服务出现问题，请联系管理员',
            type: 'error',
            duration: 5 * 1000
          })
        }
        return Promise.reject(error)
      }
    } else {
      if (error.response.data.msg !== undefined) {
        Message({
          message: error.response.data.msg,
          type: 'error',
          duration: 5 * 1000
        })
      } else {
        Message({
          message: '后台服务出现问题，请联系管理员',
          type: 'error',
          duration: 5 * 1000
        })
      }
      return Promise.reject(error)
    }
  }
)

export default service
